// groupdb
package swdb

import (
	"database/sql"
	"fmt"
	//	"io"
	"log"
	//	"net/http"
	//	"os"
	//	"reflect"
	//	"strings"
	"swim/etc"
	"swim/util/orm"

	_ "github.com/go-sql-driver/mysql"
)

var SwDbPool *sql.DB

func init() {
	/*DSN数据源名称
	  [username[:password]@][protocol[(address)]]/dbname[?param1=value1¶mN=valueN]
	  user@unix(/path/to/socket)/dbname
	  user:password@tcp(localhost:5555)/dbname?charset=utf8&autocommit=true
	  user:password@tcp([de:ad:be:ef::ca:fe]:80)/dbname?charset=utf8mb4,utf8
	  user:password@/dbname
	  无数据库: user:password@/
	*/

	var dbUrl string
	dbUrl = fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8",
		etc.DBconfiger.Uid, etc.DBconfiger.Pwd, etc.DBconfiger.Host, etc.DBconfiger.Port,
		etc.DBconfiger.Dbname)
	orm.RegisterDataBase("default", etc.DBconfiger.DbType, dbUrl, etc.DBconfiger.MaxConn/2)

	db, err := sql.Open(etc.DBconfiger.DbType, dbUrl)
	if err != nil {
		log.Fatalf("Open database error: %s\n", err)
	}
	db.SetMaxOpenConns(etc.DBconfiger.MaxConn)
	SwDbPool = db
	err = SwDbPool.Ping()
	if err != nil {
		log.Fatal(err)
	}
}
